//
// Created by korack on 25-5-13.
//

#include "Application.h"
#include "ApplicationWindow.h"

#include "ConnectWindow.h"
#include <iostream>

namespace Mp {

Application::Application()
{
  network = Glib::make_refptr_for_instance(new Network);
  // network->register_to_server();
}

Glib::RefPtr<Application>
Application::create()
{
  return Glib::make_refptr_for_instance<Application>(new Application);
}

ApplicationWindow *
Application::create_appwindow()
{
  auto window = ApplicationWindow::create();
  add_window(*window);
  window->signal_hide().connect([window] { delete window; });
  /* “连接”按钮按下后： */
  window->signal_on_connect_button_clicked.connect([this, window] {

    /* 创建“连接到服务器”窗口 */
    auto connect_window = ConnectWindow::create();

    /* 点击“连接到服务器”窗口的确认按钮后，调用 Application::connect_server */
    connect_window->signal_on_connected.connect(
      sigc::mem_fun(*this, &Application::connect_server));

    /* 确认连接成功后，更换 ApplicationWindow 的连接按钮为“取消连接” */
    connect_window->signal_on_successful_connect.connect(
      sigc::mem_fun(*window, &ApplicationWindow::hide_connect_button));

    connect_window->present();
  });
  return window;
}

bool
Application::connect_server(const std::string &server_address,
			    const int port) const
{
  try
    {
      network->connect_to_server(server_address, port);
      network->register_to_server();
    }
  catch ([[maybe_unused]] const Glib::Error &e)
    {
      return false;
    }
  return true;
}

void
Application::on_activate()
{
  try
    {
      auto app_window = create_appwindow();
      app_window->present();
    }
  catch (const Glib::Error &ex)
    {
      std::cerr << "Event::Application::on_activate(): " << ex.what()
		<< std::endl;
    }
  catch (const std::exception &ex)
    {
      std::cerr << "Event::Application::on_activate(): " << ex.what()
		<< std::endl;
    }
}

} // namespace Mp